<template>
  <div>
    <el-card v-if="showcard" class="product-enhancer-card">
      <div slot="header" class="clearfix">
        <span>配置商品提示</span>
      </div>
      <div>请在活动规则中配置商品方可开启此插件</div>
      <div style="margin-top: 50px; text-align: center">
        <el-button style="width: 180px" @click="opencard" type="primary"
          >知道了</el-button
        >
      </div>
    </el-card>
    <div v-else class="content">
      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <el-button
            icon="el-icon-circle-plus-outline"
            @click="goodsadd"
            type="primary"
            >添加商品</el-button
          >
          <el-button
            icon="el-icon-setting"
            @click="addallocation"
            type="primary"
            >批量配置</el-button
          >
        </el-col>
        <!-- <el-col :span="4" :offset="16">
              <el-button  @click="opencard" type="success">保存当前配置</el-button>
          </el-col> -->
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <el-form
            ref="allocationform"
            :model="formData"
            :rules="formRules"
            inline
          >
            <el-table
              :header-cell-style="{
                'background-color': '#f3f8fe',
                color: '#606266',
                height: '50px',
              }"
              ref="drawertable"
              v-loading="loading"
              :data="formData.check"
              @selection-change="handleSelectionChange"
              style="width: 100%"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="商品名称" align="center">
                <template slot-scope="scope">
                  <el-tooltip
                    placement="top-start"
                    :content="scope.row.goods_name + ''"
                  >
                    <div class="one_line_hidden">
                      {{ scope.row.goods_name ? scope.row.goods_name : "-" }}
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column align="center" prop="sort" label="商品分类">
                <template slot-scope="{ row }">
                  <span size="mini" v-if="row.category_name1">{{
                    row.category_name1
                  }}</span>
                </template>
              </el-table-column>

              <el-table-column label="商品图片" align="center" width="110">
                <template slot-scope="scope">
                  <el-image style="width: 40px" :src="scope.row.main_image" />
                </template>
              </el-table-column>

              <el-table-column label="所属店铺" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.mer_name }}</span>
                </template>
              </el-table-column>

              <el-table-column label="商品价格" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.retail_price }}</span>
                </template>
              </el-table-column>

              <el-table-column label="奖励规则" align="center" width="200">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.award_type`"
                    :rules="formRules.nonempty"
                  >
                    <el-select
                      v-model="scope.row.award_type"
                      placeholder="请选择"
                    >
                      <el-option
                        label="按支付金额发放"
                        :value="1"
                      ></el-option>
                      <el-option
                        label="按商品利润发放"
                        :value="2"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="送积分数" align="center" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.integral_num`"
                    :rules="formRules.moneynumber"
                  >
                    <el-input
                      v-model="scope.row.integral_num"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="发放时间" align="center" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.node_day`"
                    :rules="formRules.timeFieldName"
                  >
                    <el-input v-model="scope.row.node_day" placeholder="请输入">
                      <template slot="prepend">T+</template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="时间节点" align="center" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`check.${scope.$index}.node_type`"
                    :rules="formRules.nonempty"
                  >
                    <el-select
                      v-model="scope.row.node_type"
                      placeholder="请选择"
                    >
                      <el-option label="支付成功" :value="1"></el-option>
                      <el-option label="确认收货" :value="2"></el-option>
                      <el-option label="评价" :value="3"></el-option>
                      <el-option label="过售后期" :value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" width="110">
                <template slot-scope="scope">
                  <el-button
                    @click="goodsremove(scope.row.id)"
                    v-if="formData.check.length == 1 ? false : true"
                    size="mini"
                    type="danger"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <el-drawer
      :modal-append-to-body="false"
      :append-to-body="true"
      title="批量配置"
      size="70%"
      class="box-drawer"
      :with-header="false"
      :visible.sync="showallocation"
      :show-close="true"
      @close="closedinvitation"
    >
      <!-- 头部-->
      <div style="position: relative">
        <div
          class="drawerTitle"
          style="background-color: #409eff !important; padding: 13px 15px"
        >
          <span>批量配置</span>
          <div class="close" @click="closedinvitation" style="top: 12px">
            <i class="el-icon-close" style="font-size: 22px" />
          </div>
        </div>
      </div>
      <el-alert
        style="margin-bottom: 20px"
        title="说明:"
        type="warning"
        :closable="false"
      >
        说明：针对所选中的批量商品进行统一配置，配置完成后，选中商品在列表中的限购字段同意赋值
      </el-alert>
      <el-form style="padding: 20px" :model="drawerForm" ref="drawerForm">
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="赠送积分"
              prop="integral_num"
              :rules="formRules.moneynumber"
            >
              <el-input
                style="width: 180px"
                v-model="drawerForm.integral_num"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="奖励规则"
              prop="award_type"
              :rules="formRules.nonempty"
            >
              <el-select v-model="drawerForm.award_type" placeholder="请选择">
                <el-option label="按支付金额发放" :value="1"></el-option>
                <el-option label="按商品利润发放" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="发放时间"
              prop="node_day"
              :rules="formRules.newFieldName"
            >
              <el-input
                style="width: 280px"
                v-model="drawerForm.node_day"
                placeholder="请输入"
              >
                <template slot="prepend">T+</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="时间节点"
              prop="node_type"
              :rules="formRules.nonempty"
            >
              <el-select v-model="drawerForm.node_type" placeholder="请选择">
                <el-option label="支付成功" :value="1"></el-option>
                <el-option label="确认收货" :value="2"></el-option>
                <el-option label="评价" :value="3"></el-option>
                <el-option label="过售后期" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 16px">
          <el-button @click="subpul" style="width: 80px" type="primary"
            >保存</el-button
          >
          <el-button
            @click="resatting"
            style="width: 80px; margin-left: 30px"
            type="info"
            >重置</el-button
          >
        </el-row>
      </el-form>
    </el-drawer>

    <!-- 添加商品 -->
    <addproduct
      ref="addproduct"
      v-if="ifShowadd"
      :shappingid="shappingid"
      :goodsIds="ADDgoods"
    ></addproduct>
  </div>
</template>

<script>
import addproduct from "./components/addremovelist.vue";

import { listGood } from "@/api/index";

export default {
  props: ["shapdata", "shappingid", "editdata"],
  components: {
    addproduct,
  },
  data() {
    return {
      loading: true,
      showallocation: false,
      editfordata:'',
      ifShowadd: false,
      goodsIds: [], //选择好的配置商品
      removeids: [], //移除的商品
      ADDgoods: [], //添加的商品
      multipleSelection: [], //选中的商品
      productConfigTitle: "配置奖池商品",
      addproductTitle: "添加商品",
      showcard: true,
      drawerForm: {
        integral_num: 0,
        award_type: 1,
        node_day: 0,
        node_type: 1,
      },
      isshow:'',
      formData: {
        check: [],
      },
      formRules: {
        timeFieldName: [
          {
            required: false,
            validator: (rule, value, callback) => {
              let req = /^(0|[1-9]|1[0-9]|20)$/;
              if (req.test(value)) {
                callback();
              } else {
                callback(new Error("请输入0-20正整数"));
              }
            },
            trigger: "change",
          },
        ],
        moneynumber: [
          {
            required: false,
            validator: (rule, value, callback) => {
              let req = /^\d+(\.\d{1,2})?%?$/;
              let regex = /%/;
              if (regex.test(value)) {
                let jsx = /^\d+(\.\d{1,2})?%?$/;
                if (jsx.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多两位正小数"));
                }
              } else {
                if (req.test(value)) {
                  if (Number(value) > 999999) {
                    return callback(new Error("积分不能大于999999"));
                  }
                  callback();
                } else {
                  callback(new Error("保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        nonempty: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
      },
      eventsForm: {
        activity_id: "",
        activity_type: 5,
        goods_id: [],
      },
    };
  },

  watch: {
    shapdata: {
      handler(newValue, oldValue) {
        this.isshow = newValue
        this.ADDgoods = newValue;
        this.contrast(newValue)
        this.opencard();
      },
      deep: true,
    },
    editdata: {
      handler(newValue, oldValue) {
        this.editfordata = newValue;
        this.getperopdata()
      },
      deep: true,
    },

    "formData.check": {
      handler(newValue, oldValue) {
        this.$emit("updateCheckData", newValue);
      },
      deep: true,
    },
  },

  mounted() {
  },
  methods: {
    // 现在列表对比规则列表
    contrast(val){
      if(this.editdata.is_open) {
        this.goodsIds  = this.goodsIds.filter(id => val.includes(id));
        this.getGoodsList()
      }else{
        this.goodsIds  = this.goodsIds.filter(id => val.includes(id));
        this.getGoodsList()
        let result =this.ADDgoods.filter(id => !this.goodsIds.includes(id));
        this.ADDgoods = result
      }
    },

        // 开启
    opencard() {
      if (this.isshow.length != 0) {
        this.showcard = false;
        // this.getGoodsList()
      } else {
        this.$emit("child-event", "third");
        this.$message({
          message: "请先选择指定商品",
        });
        this.showcard = true;
        this.getGoodsList()
      }
    },
    // 获取修改的值
    getperopdata(val) {
      this.editfordata.goods_list.forEach((item) => {
        this.goodsIds.push(item.goods_id);
      });
      this.getGoodsList();

    },

    //批量保存
    subpul() {
      this.multipleSelection.forEach((item) => {
        item.integral_num = this.drawerForm.integral_num;
        item.award_type = this.drawerForm.award_type;
        item.node_day = this.drawerForm.node_day;
        item.node_type = this.drawerForm.node_type;
      });
      this.$message({
        message: "配置成功",
        type: "success",
      });
      this.toggleSelection();
      this.showallocation = false;
    },
    resatting() {
      this.drawerForm = {
        integral_num: 0,
        award_type: 1,
        node_day: 0,
        node_type: 1,
      };
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.drawertable.toggleRowSelection(row);
        });
      } else {
        this.$refs.drawertable.clearSelection();
      }
    },
    // 获取列表
    getGoodsList() {
      this.eventsForm.goods_id = this.goodsIds;
      this.eventsForm.activity_id = this.shappingid;
      listGood(this.eventsForm).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          return this.$messages.error(res.msg);
        }
        this.formData.check = res.data;
        this.formData.check.forEach((item) => {
          const defaults = {
            award_type: 1,
            integral_num: 0,
            node_day: 0,
            node_type: 1,
          };
          Object.keys(defaults).forEach((key) => {
            if (item[key] === "") {
              item[key] = defaults[key];
            }
          });
        });
        this.loading = false;
      });
    },

    //打开配置
    addallocation() {
      if (this.multipleSelection.length <= 0) {
        this.$messages.warning("请选择商品");
      } else {
        this.showallocation = true;
      }
    },
    //删除商品
    goodsremove(idToRemove) {
     
      const filteredGoodsIds = this.goodsIds.filter((id) => id !== idToRemove);
      this.goodsIds = filteredGoodsIds;
      this.getGoodsList()
      this.ADDgoods.push(idToRemove);
    },
    //添加商品弹窗关闭
    closeaddproduct() {
      this.ifShowadd = false;
    },
    closedinvitation() {
      this.toggleSelection();
      this.showallocation = false;
    },
    //拿到添加商品的回调
    addproductWay(row) {
      row.forEach((item) => {
        this.formData.check.push(item);
      });
      row.forEach((item) => {
        this.goodsIds.push(item.id);
        this.ADDgoods = this.ADDgoods.filter((removeId) => {
          return !row.some((rowItem) => rowItem.id === removeId);
        });
      });
      this.getGoodsList();
      this.$message({
        message: "添加成功",
        type: "success",
      });
    },
    addproductRowWay(row) {
      // this.goodsIds = [...this.goodsIds, ...row];
    },
    //添加商品弹窗打开
    goodsadd() {
      this.ifShowadd = true;
      let result =this.ADDgoods.filter(id => !this.goodsIds.includes(id));
      this.ADDgoods = result
    },

    // 选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 列表分页
    handleSizeChange(val) {
      this.searchForm.count = val;
      //   this.getListWay()
    },
    // 列表分页
    handleCurrentChange(val) {
      this.searchForm.page = val;
      //   this.getListWay()
    },
  },
};
</script>

<style>
.el-card__header {
  padding: 0;
}
/* 设置滚动条的宽度和颜色 */
.el-table__body-wrapper {
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: #bbbbbb #eee; /* Firefox */
}

/* 滚动条的整体样式 */
.el-table__body-wrapper::-webkit-scrollbar {
  width: 12px;
}

/* 滚动条轨道的样式 */
.el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #eee;
}

/* 滚动条滑块的样式 */
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #bbbbbb;
  border: 3px solid #fff;
  border-radius: 10px;
}

/* 兼容 IE 浏览器 */
.el-table__body-wrapper {
  scrollbar-base-color: #eee;
  scrollbar-arrow-color: #bbb;
  scrollbar-3dlight-color: #bbb;
  scrollbar-darkshadow-color: #bbb;
  scrollbar-face-color: #bbb;
  scrollbar-highlight-color: #bbb;
  scrollbar-shadow-color: #bbb;
}
</style>

<style scoped>
.content {
  padding: 20px;
}

.product-enhancer-card {
  width: 100%;
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.product-enhancer-card .clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 20px;
}
</style>
